/*
 *  The MIT License
 * 
 *  Copyright 2011 Edwin Bratini <edwin.bratini@gmail.com>.
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */

/*
 * BusquedaRapida.java
 *
 * Created on 05/12/2011, 10:40:03 AM
 */
package com.prebea.syscafil.ui;

import com.prebea.syscafil.business.AfiliadoManager;
import com.prebea.syscafil.business.CategoriaPlanManager;
import com.prebea.syscafil.business.DependienteManager;
import com.prebea.syscafil.business.EmpresaManager;
import com.prebea.syscafil.business.NumberFieldValidator;
import com.prebea.syscafil.business.PlanManager;
import com.prebea.syscafil.model.entities.Afiliado;
import com.prebea.syscafil.model.entities.Dependiente;
import com.prebea.syscafil.model.entities.Empresa;
import com.prebea.syscafil.model.entities.Plan;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Edwin Bratini <edwin.bratini@gmail.com>
 */
public class BusquedaRapida extends javax.swing.JDialog {

    private Serializable entityToSearch;
    private Object entitySelectedId;

    /** Creates new form BusquedaRapida */
    public BusquedaRapida(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public BusquedaRapida(java.awt.Frame parent, boolean modal, Serializable entityToSearch) {
        this(parent, modal);
        this.entityToSearch = entityToSearch;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        pnlOpBusqueda = new javax.swing.JPanel();
        chkFiltro = new javax.swing.JCheckBox();
        rdbField1 = new javax.swing.JRadioButton();
        rdbField2 = new javax.swing.JRadioButton();
        rdbField3 = new javax.swing.JRadioButton();
        lblEntidades = new javax.swing.JLabel();
        scrEntidades = new javax.swing.JScrollPane();
        jtbEntidades = new javax.swing.JTable();
        btnBuscar = new javax.swing.JButton();
        txtBusqueda = new javax.swing.JTextField();
        btnSeleccionar = new javax.swing.JButton();
        lblResultadosBusqueda = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        pnlOpBusqueda.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones de Busqueda"));
        pnlOpBusqueda.setName("pnlOpBusqueda"); // NOI18N

        chkFiltro.setText("Filtro");
        chkFiltro.setName("chkFiltro"); // NOI18N
        chkFiltro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkFiltroActionPerformed(evt);
            }
        });

        buttonGroup1.add(rdbField1);
        rdbField1.setSelected(true);
        rdbField1.setText("Field 1");
        rdbField1.setName("rdbField1"); // NOI18N

        buttonGroup1.add(rdbField2);
        rdbField2.setText("Field 2");
        rdbField2.setName("rdbField2"); // NOI18N

        buttonGroup1.add(rdbField3);
        rdbField3.setText("Field 3");
        rdbField3.setName("rdbField3"); // NOI18N

        javax.swing.GroupLayout pnlOpBusquedaLayout = new javax.swing.GroupLayout(pnlOpBusqueda);
        pnlOpBusqueda.setLayout(pnlOpBusquedaLayout);
        pnlOpBusquedaLayout.setHorizontalGroup(
            pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlOpBusquedaLayout.createSequentialGroup()
                .addGroup(pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlOpBusquedaLayout.createSequentialGroup()
                        .addComponent(rdbField1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rdbField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rdbField3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(chkFiltro))
                .addContainerGap(17, Short.MAX_VALUE))
        );
        pnlOpBusquedaLayout.setVerticalGroup(
            pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlOpBusquedaLayout.createSequentialGroup()
                .addComponent(chkFiltro)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 3, Short.MAX_VALUE)
                .addGroup(pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rdbField1)
                    .addComponent(rdbField2)
                    .addComponent(rdbField3)))
        );

        lblEntidades.setText("Entidades");

        scrEntidades.setName("scrEntidades"); // NOI18N

        jtbEntidades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        scrEntidades.setViewportView(jtbEntidades);

        btnBuscar.setText("Buscar");
        btnBuscar.setName("btnBuscar"); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        txtBusqueda.setName("txtBusqueda"); // NOI18N
        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyPressed(evt);
            }
        });

        btnSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/imagenes/ok.png"))); // NOI18N
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        lblResultadosBusqueda.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(scrEntidades, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(lblEntidades)
                        .addGap(84, 84, 84)
                        .addComponent(lblResultadosBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                        .addComponent(btnSeleccionar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(pnlOpBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnBuscar)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSeleccionar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE))
                            .addComponent(pnlOpBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(21, 21, 21)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblEntidades)
                            .addComponent(lblResultadosBusqueda))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrEntidades, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 535, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 273, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(1, 1, 1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        // TODO add your handling code here:
        if (jtbEntidades.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "Primero seleccione registro", "Seleccion", JOptionPane.ERROR_MESSAGE);
            return;
        }
        entitySelectedId = jtbEntidades.getValueAt(jtbEntidades.getSelectedRow(), 0);
        this.dispose();
}//GEN-LAST:event_btnSeleccionarActionPerformed

    private void showEntityOnJtable(Object[][] data) {
        Object[] cols = new Object[jtbEntidades.getColumnCount()];
        for (int i = 0; i < jtbEntidades.getColumnCount(); i++) {
            cols[i] = jtbEntidades.getColumnName(i);
        }
        DefaultTableModel dtm = new DefaultTableModel(data, cols) {
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };
        jtbEntidades.setModel(dtm);
    }

    private void showNoResultMessage() {
        lblResultadosBusqueda.setText("No hubo resultados");
        lblResultadosBusqueda.setForeground(Color.red);
        new Thread(new LabelToolTipShower(lblResultadosBusqueda, 3000)).start();
        return;
    }

    private boolean isEntityNull(Serializable entity) {
        if (entity != null) {
            return false;
        } else {
            showNoResultMessage();
            showEntityOnJtable(new Object[][]{});
            return true;
        }
    }

    private boolean isIdFieldValid() {
        if (!new NumberFieldValidator().validate(txtBusqueda.getText())) {
            JOptionPane.showMessageDialog(this, "Solo numeros para busqueda por campo id", "Busqueda", JOptionPane.ERROR_MESSAGE);
            return false;
        } else {
            return true;
        }
    }

    private void doSearch() {
        if (txtBusqueda.getText().equalsIgnoreCase("*")) {
            loadEntities();
            return;
        } else if (txtBusqueda.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Introduzca texto a buscar", "Busqueda", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (entityToSearch instanceof Empresa) {
            EmpresaManager em = new EmpresaManager();
            Empresa empresaSearched = null;
            if (getRdbField1().isSelected()) {
                if (!isIdFieldValid()) {
                    return;
                }
                empresaSearched = em.getEmpresaById(Integer.parseInt(txtBusqueda.getText()));
                if (isEntityNull(empresaSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {empresaSearched.getEmpId(), empresaSearched.getEmpDni(), empresaSearched.getEmpRazonSocial()}
                        });
            } else if (getRdbField2().isSelected()) {
                empresaSearched = em.getEmpresaByDNI(txtBusqueda.getText());
                if (isEntityNull(empresaSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {empresaSearched.getEmpId(), empresaSearched.getEmpDni(), empresaSearched.getEmpRazonSocial()}
                        });
            } else {
                List<Empresa> empresas = em.getEmpresaByRazonSocial(txtBusqueda.getText());
                if (empresas != null && empresas.size() < 1) {
                    showNoResultMessage();
                    showEntityOnJtable(new Object[][]{});
                    return;
                }
                Object[][] rows = new Object[empresas.size()][];
                int i = 0;
                for (Empresa emp : empresas) {
                    rows[i] = new Object[]{emp.getEmpId(), emp.getEmpDni(), emp.getEmpRazonSocial()};
                    i++;
                }
                showEntityOnJtable(rows);
            }
        } else if (entityToSearch instanceof Afiliado) {
            AfiliadoManager am = new AfiliadoManager();
            Afiliado afiliadoSearched = null;
            if (getRdbField1().isSelected()) {
                if (!isIdFieldValid()) {
                    return;
                }
                afiliadoSearched = am.getAfiliadoById(Integer.parseInt(txtBusqueda.getText()));
                if (isEntityNull(afiliadoSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {afiliadoSearched.getAflId(), afiliadoSearched.getAflDni(), String.format("%s, %s",
                                afiliadoSearched.getAflApellido(), afiliadoSearched.getAflNombre())}
                        });
            } else if (getRdbField2().isSelected()) {
                afiliadoSearched = am.getAfiliadoByDNI(txtBusqueda.getText());
                if (isEntityNull(afiliadoSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {afiliadoSearched.getAflId(), afiliadoSearched.getAflDni(), String.format("%s, %s",
                                afiliadoSearched.getAflApellido(), afiliadoSearched.getAflNombre())}
                        });
            } else {
                List<Afiliado> afiliados = am.getAfiliadoByApellido(txtBusqueda.getText());
                if(afiliados != null && afiliados.size() < 1) {
                    showNoResultMessage();
                    showEntityOnJtable(new Object[][]{});
                    return;
                }
                Object[][] rows = new Object[afiliados.size()][];
                int i = 0;
                for (Afiliado afil : afiliados) {
                    rows[i] = new Object[]{afil.getAflId(), afil.getAflDni(), String.format("%s, %s", afil.getAflApellido(),
                                afil.getAflNombre())};
                    i++;
                }
                showEntityOnJtable(rows);
            }
        } else if (entityToSearch instanceof Dependiente) {
            DependienteManager dm = new DependienteManager();
            Dependiente dependienteSearched = null;
            if (getRdbField1().isSelected()) {
                if (!isIdFieldValid()) {
                    return;
                }
                dependienteSearched = dm.getDependienteById(Integer.parseInt(txtBusqueda.getText()));
                if (isEntityNull(dependienteSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {dependienteSearched.getDepId(), dependienteSearched.getDepDni(), String.format("%s, %s",
                                dependienteSearched.getDepApellido(), dependienteSearched.getDepNombre())}
                        });
            } else if (getRdbField2().isSelected()) {
                dependienteSearched = dm.getDependienteByDNI(txtBusqueda.getText());
                if (isEntityNull(dependienteSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {dependienteSearched.getDepId(), dependienteSearched.getDepDni(), String.format("%s, %s",
                                dependienteSearched.getDepApellido(), dependienteSearched.getDepNombre())}
                        });
            } else {
                List<Dependiente> dependientes = dm.getDependienteByApellido(txtBusqueda.getText());
                if(dependientes != null && dependientes.size() < 1) {
                    showNoResultMessage();
                    showEntityOnJtable(new Object[][]{});
                    return;
                }
                Object[][] rows = new Object[dependientes.size()][];
                int i = 0;
                for (Dependiente dep : dependientes) {
                    rows[i] = new Object[]
                                {dep.getDepId(), dep.getDepDni(), String.format("%s, %s", dep.getDepApellido(),
                                    dep.getDepNombre())};
                    i++;
                }
                showEntityOnJtable(rows);
            }
        } else if (entityToSearch instanceof Plan) {
            PlanManager pm = new PlanManager();
            Plan planSearched = null;
            if (getRdbField1().isSelected()) {
                if (!isIdFieldValid()) {
                    return;
                }
                planSearched = pm.getPlanById(Integer.parseInt(txtBusqueda.getText()));
                if (isEntityNull(planSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {planSearched.getPlnId(), planSearched.getPlnNombre(), planSearched.getCategoriaPlan().getCapNombre()}
                        });
            } else if (getRdbField2().isSelected()) {
                planSearched = pm.getPlanByNombre(txtBusqueda.getText());
                if (isEntityNull(planSearched)) {
                    return;
                }
                showEntityOnJtable(new Object[][]{
                            {planSearched.getPlnId(), planSearched.getPlnNombre(), planSearched.getCategoriaPlan().getCapNombre()}
                        });
            } else {
                List<Plan> planes = pm.getPlanByCategoriaPlan(new CategoriaPlanManager().getCategoriaPlanByNombre(txtBusqueda.getText()));
                if(planes != null && planes.size() < 1) {
                    showNoResultMessage();
                    showEntityOnJtable(new Object[][]{});
                    return;
                }
                Object[][] rows = new Object[planes.size()][];
                int i = 0;
                for (Plan plan : planes) {
                    rows[i] = new Object[][]{
                                {plan.getPlnId(), plan.getPlnNombre(), plan.getCategoriaPlan().getCapNombre()}
                            };
                    i++;
                }
                showEntityOnJtable(rows);
            }
        }
    }

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        doSearch();
}//GEN-LAST:event_btnBuscarActionPerformed

    private void chkFiltroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkFiltroActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_chkFiltroActionPerformed

    private Object[][] getDataFromEntity(Serializable entity) {
        Object[][] data = null;
        int i = 0;
        if (entity instanceof Empresa) {
            List<Empresa> empresas = new EmpresaManager().getEmpresas();
            if (empresas != null && empresas.size() > 0) {
                data = new Object[empresas.size()][];
                for (Empresa emp : empresas) {
                    data[i] = new Object[]{emp.getEmpId(), emp.getEmpDni(), emp.getEmpRazonSocial()};
                    i++;
                }
            }
        } else if (entity instanceof Afiliado) {
            List<Afiliado> afiliados = new AfiliadoManager().getAfiliados();
            if (afiliados != null && afiliados.size() > 0) {
                data = new Object[afiliados.size()][];
                for (Afiliado afil : afiliados) {
                    data[i] = new Object[]{afil.getAflId(), afil.getAflDni(), String.format("%s, %s", afil.getAflApellido(), afil.getAflNombre())};
                    i++;
                }
            }
        } else if (entity instanceof Dependiente) {
            List<Dependiente> dependientes = new DependienteManager().getDependientes();
            if (dependientes != null && dependientes.size() > 0) {
                data = new Object[dependientes.size()][];
                for (Dependiente dep : dependientes) {
                    data[i] = new Object[]{dep.getDepId(), dep.getDepDni(), String.format("%s, %s", dep.getDepApellido(), dep.getDepNombre())};
                    i++;
                }
            }
        } else if (entity instanceof Plan) {
            List<Plan> planes = new PlanManager().getPlanes();
            if (planes != null && planes.size() > 0) {
                data = new Object[planes.size()][];
                for (Plan plan : planes) {
                    data[i] = new Object[]{plan.getPlnId(), plan.getPlnNombre(), plan.getCategoriaPlan().getCapNombre()};
                    i++;
                }
            }
        }

        return data;
    }

    private void loadEntities() {
        if (entityToSearch != null) {
            jtbEntidades.setColumnModel(new DefaultTableColumnModel() {

                public void moveColumn(int columnIndex, int newIndex) {
                    if (columnIndex == 0 || newIndex == 0) {
                        return;
                    }
                    super.moveColumn(columnIndex, newIndex);
                }
            });
            DefaultTableModel dtm = new DefaultTableModel(getDataFromEntity(entityToSearch),
                    new Object[]{getRdbField1().getText(), getRdbField2().getText(),
                    ((entityToSearch instanceof Afiliado || entityToSearch instanceof Dependiente) ? "Nombre" : getRdbField3().getText())}) {

                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    return false;
                }
            };

            jtbEntidades.setModel(dtm);
        }
    }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        loadEntities();
    }//GEN-LAST:event_formWindowOpened

    private void txtBusquedaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnBuscar.doClick();
        }
    }//GEN-LAST:event_txtBusquedaKeyPressed

    public void setEntityToSearch(Serializable entityToSearch) {
        this.entityToSearch = entityToSearch;
    }

    public JButton getBtnBuscar() {
        return btnBuscar;
    }

    public void setBtnBuscar(JButton btnBuscar) {
        this.btnBuscar = btnBuscar;
    }

    public JCheckBox getChkFiltro() {
        return chkFiltro;
    }

    public void setChkFiltro(JCheckBox chkFiltro) {
        this.chkFiltro = chkFiltro;
    }

    public JButton getBtnSeleccionar() {
        return btnSeleccionar;
    }

    public void setBtnSeleccionar(JButton btnSeleccionar) {
        this.btnSeleccionar = btnSeleccionar;
    }

    public ButtonGroup getButtonGroup1() {
        return buttonGroup1;
    }

    public void setButtonGroup1(ButtonGroup buttonGroup1) {
        this.buttonGroup1 = buttonGroup1;
    }

    public JLabel getLblResultadosBusqueda() {
        return lblResultadosBusqueda;
    }

    public void setLblResultadosBusqueda(JLabel lblResultadosBusqueda) {
        this.lblResultadosBusqueda = lblResultadosBusqueda;
    }

    public JPanel getjPanel1() {
        return jPanel1;
    }

    public void setjPanel1(JPanel jPanel1) {
        this.jPanel1 = jPanel1;
    }

    public JTable getJtbEntidades() {
        return jtbEntidades;
    }

    public void setJtbEntidades(JTable jtbEntidades) {
        this.jtbEntidades = jtbEntidades;
    }

    public JLabel getLblEntidades() {
        return lblEntidades;
    }

    public void setLblEntidades(JLabel lblEntidades) {
        this.lblEntidades = lblEntidades;
    }

    public JPanel getPnlOpBusqueda() {
        return pnlOpBusqueda;
    }

    public void setPnlOpBusqueda(JPanel pnlOpBusqueda) {
        this.pnlOpBusqueda = pnlOpBusqueda;
    }

    public JRadioButton getRdbField1() {
        return rdbField1;
    }

    public void setRdbField1(JRadioButton rdbField1) {
        this.rdbField1 = rdbField1;
    }

    public JRadioButton getRdbField2() {
        return rdbField2;
    }

    public void setRdbField2(JRadioButton rdbField2) {
        this.rdbField2 = rdbField2;
    }

    public JRadioButton getRdbField3() {
        return rdbField3;
    }

    public void setRdbField3(JRadioButton rdbField3) {
        this.rdbField3 = rdbField3;
    }

    public JScrollPane getScrEntidades() {
        return scrEntidades;
    }

    public void setScrEntidades(JScrollPane scrEntidades) {
        this.scrEntidades = scrEntidades;
    }

    public JTextField getTxtBusqueda() {
        return txtBusqueda;
    }

    public void setTxtBusqueda(JTextField txtBusqueda) {
        this.txtBusqueda = txtBusqueda;
    }

    public Object getEntitySelectedId() {
        return entitySelectedId;
    }

    public Serializable getEntityToSearch() {
        return entityToSearch;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                BusquedaRapida dialog = new BusquedaRapida(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JCheckBox chkFiltro;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTable jtbEntidades;
    private javax.swing.JLabel lblEntidades;
    private javax.swing.JLabel lblResultadosBusqueda;
    private javax.swing.JPanel pnlOpBusqueda;
    private javax.swing.JRadioButton rdbField1;
    private javax.swing.JRadioButton rdbField2;
    private javax.swing.JRadioButton rdbField3;
    private javax.swing.JScrollPane scrEntidades;
    private javax.swing.JTextField txtBusqueda;
    // End of variables declaration//GEN-END:variables
}
